<?php

/**
 * This is the model class for table "order".
 *
 * The followings are the available columns in table 'order':
 * @property integer $order_id
 * @property string $shipping_address
 * @property string $shipping_name
 * @property string $shipping_phone
 * @property string $shipping_email
 * @property string $payment_address
 * @property string $payment_name
 * @property string $payment_phone
 * @property string $payment_email
 * @property string $created
 * @property integer $user_id
 * @property string $total
 * @property string $comment
 */
class Order extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'order';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('user_id', 'numerical', 'integerOnly' => true),
            array('shipping_address, shipping_name, shipping_phone, shipping_email, payment_address, payment_name, payment_phone, payment_email', 'length', 'max' => 255),
            array('total', 'length', 'max' => 10),
            array('created, comment', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('order_id, shipping_address, shipping_name, shipping_phone, shipping_email, payment_address, payment_name, payment_phone, payment_email, created, user_id, total, comment', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'details' => array(self::HAS_MANY, 'Detail', 'order_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'order_id' => 'Order',
            'shipping_address' => 'Shipping Address',
            'shipping_name' => 'Shipping Name',
            'shipping_phone' => 'Shipping Phone',
            'shipping_email' => 'Shipping Email',
            'payment_address' => 'Payment Address',
            'payment_name' => 'Payment Name',
            'payment_phone' => 'Payment Phone',
            'payment_email' => 'Payment Email',
            'created' => 'Created',
            'user_id' => 'User',
            'total' => 'Total',
            'comment' => 'Comment',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('order_id', $this->order_id);
        $criteria->compare('shipping_address', $this->shipping_address, true);
        $criteria->compare('shipping_name', $this->shipping_name, true);
        $criteria->compare('shipping_phone', $this->shipping_phone, true);
        $criteria->compare('shipping_email', $this->shipping_email, true);
        $criteria->compare('payment_address', $this->payment_address, true);
        $criteria->compare('payment_name', $this->payment_name, true);
        $criteria->compare('payment_phone', $this->payment_phone, true);
        $criteria->compare('payment_email', $this->payment_email, true);
        $criteria->compare('created', $this->created, true);
        $criteria->compare('user_id', $this->user_id);
        $criteria->compare('total', $this->total, true);
        $criteria->compare('comment', $this->comment, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Order the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * 
     */
    public static function saveOrder($shipping, $payment, $products, $user_id) {
        $order = new Order();
        $order->shipping_address = $shipping->address;
        $order->shipping_email = $shipping->email;
        $order->shipping_name = $shipping->name;
        $order->shipping_phone = $shipping->phone;
        $order->comment = $payment->comment;
        $order->payment_address = $payment->address;
        $order->payment_email = $payment->email;
        $order->payment_name = $payment->name;
        $order->payment_phone = $payment->phone;
        $order->created = date('Y-m-d h:i:s');
        $order->user_id = $user_id;

        $details = array();
        $total = 0;
        foreach ($products as $item) {
            $total_item = $item['product']->getPrice() * $item['quantity'];
            $total += $total_item;
            $details[] = array(
                'product_id' => $item['product']->product_id,
                'quantity' => $item['quantity'],
                'price' => $item['product']->getPrice(),
                'property' => serialize($item['simpleAttributes']),
                'total' => $total_item,
            );
            $quantity = $item['product']->quantity - $item['quantity'] >= 0?$item['product']->quantity - $item['quantity']:0;
            $item['product']->buy = $item['product']->buy + 1;
            $item['product']->quantity = $quantity;
            $item['product']->save();
        }

        $order->total = $total;
        if ($order->save()) {
            foreach ($details as $item) {
                $detail = new Detail();
                $detail->attributes = $item;
                $detail->order_id = $order->order_id;
                $detail->save();
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 
     */
    public static function getOrderOfUser($userId) {
        $criteria = new CDbCriteria;
        $criteria->compare('user_id',$userId);
        $criteria->order = "created DESC";
        return self::model()->findAll($criteria);
    }

}
